package com.hengpeng.itfinoss.service.borrowInfo.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.en.BorrowStatus;
import com.hengpeng.itfinbase.en.InputStatus;
import com.hengpeng.itfinbase.en.InvestStatus;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoStatus;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.service.borrowInfo.BorrowInfoService;

@Lazy
@Service
public class BorrowInfoServiceImpl implements BorrowInfoService {
    @Autowired
    private ServiceFactory serviceFactory;

    @Override
    public ServiceResult<List<BorrowInfo>> queryList(String borrowName, String borrowUserName, Date start, Date end,
            BorrowStatus[] status,InputStatus[] inputStatus,Integer pageIndex, Integer pageSize) {
        DynamicQuery query = new DynamicQuery(BorrowInfo.class);
        if (!StringHelper.isEmpty(borrowName)) {
            query.like("borrowName", "%" + borrowName + "%");
        }
        if (!StringHelper.isEmpty(borrowUserName)) {
            query.eq("borrowUserName", borrowUserName);
        }
        if (status != null) {
            query.inArray("status", status);
        }
        if(null != inputStatus){
            query.inArray("inputStatus", inputStatus);
        }
        if (start != null) {
            query.ge("createTime", start);
        }
        if (end != null) {
            query.le("createTime", end);
        }
        query.desc("createTime");
        query.setPageIndex(pageIndex);
        query.setPageSize(pageSize);
        return new ServiceResult<List<BorrowInfo>>(serviceFactory.getPersistService().find(BorrowInfo.class, query));
    }

    @Override
    public ServiceResult<Long> queryCount(String borrowName, String borrowUserName, Date start, Date end,
            BorrowStatus[] status,InputStatus[] inputStatus) {
        DynamicQuery query = new DynamicQuery(BorrowInfo.class);
        if (!StringHelper.isEmpty(borrowName)) {
            query.like("borrowName", "%" + borrowName + "%");
        }
        if (!StringHelper.isEmpty(borrowUserName)) {
            query.eq("borrowUserName", borrowUserName);
        }
        if (status != null) {
            query.inArray("status", status);
        }
        if(null != inputStatus){
            query.inArray("inputStatus", inputStatus);
        }
        if (start != null) {
            query.ge("createTime", start);
        }
        if (end != null) {
            query.le("createTime", end);
        }
        return new ServiceResult<Long>(serviceFactory.getPersistService().findPageCount(query, null));
    }

    @Override
    public ServiceResult<List<InvestInfo>> queryInvestList(Long borrowId, Integer pageIndex, Integer pageSize) {
        DynamicQuery query = new DynamicQuery(InvestInfo.class);
        query.eq("borrowInfoId", borrowId);
        query.setPageIndex(pageIndex);
        query.setPageSize(pageSize);
        return new ServiceResult<List<InvestInfo>>(serviceFactory.getPersistService().find(InvestInfo.class, query));
    }

    @Override
    public ServiceResult<Long> queryInvestCount(Long borrowId) {
        DynamicQuery query = new DynamicQuery(InvestInfo.class);
        query.eq("borrowInfoId", borrowId);
        return new ServiceResult<Long>(serviceFactory.getPersistService().findPageCount(query, null));
    }

    @Override
    public BorrowInfo getBorrowInfo(Long id, BorrowStatus status) {
        DynamicQuery query = new DynamicQuery(BorrowInfo.class);
        query.eq("id", id);
        if (status != null) {
            query.eq("status", status);
        }
        List<BorrowInfo> list = serviceFactory.getPersistService().find(BorrowInfo.class, query);
        return list == null || list.size() < 1 ? null : list.get(0);
    }

    /**
     * 后台平台交易总览
     * 
     * @return
     */
    @Override
    public ServiceResult<Map<String, String>> getBorrowInfoView() {
        ServiceResult<Map<String, String>> serviceResult = new ServiceResult<Map<String, String>>();
        // 已发布的标的数量
        BorrowStatus[] isPublishStatus = { BorrowStatus.RAISE, BorrowStatus.END, BorrowStatus.LOANING,
                BorrowStatus.REPAYMENTING, BorrowStatus.REPAYMENTED };
        String isPublishBorrowInfoCount = this.getBorrowInfoCountByStatus(isPublishStatus, null) + "";

        // 今日新增借款标申请
        BorrowStatus[] isApplyStatus = { BorrowStatus.WAITING, BorrowStatus.UNPASS, BorrowStatus.PASS,
                BorrowStatus.SCHEDULED };
        String todayBorrowInfoCount = this.getBorrowInfoCountByStatus(isApplyStatus, new Date()) + "";

        // 共有注册会员
        String userCount = this.getUserCount(UserInfoStatus.NORMAL, null) + "";
        String todayRegisterCount = this.getUserCount(UserInfoStatus.NORMAL, new Date()) + "";

        // 统计交易数
        String tradeAccount = this.getTradeAccount(InvestStatus.SUCESS);

        // //统计交易总额
        String tradeAmount = this.getTradeAmount(InvestStatus.SUCESS);
        Map<String, String> map = new java.util.HashMap<String, String>();
        map.put("isPublishBorrowInfoCount", isPublishBorrowInfoCount);
        map.put("todayBorrowInfoCount", todayBorrowInfoCount);
        map.put("userCount", userCount);
        map.put("todayRegisterCount", todayRegisterCount);
        map.put("tradeAccount", tradeAccount);
        map.put("tradeAmount", tradeAmount);
        serviceResult.setReturnValue(map);
        serviceResult.setIsSuccess(true);
        serviceResult.setCode(Constant.TRANSACTION_RESPONSE_CODE_SUCCESS);
        return serviceResult;
    }

    // 统计不同标的数量
    private long getBorrowInfoCountByStatus(BorrowStatus[] status, Date date) {
        DynamicQuery query = new DynamicQuery(BorrowInfo.class);
        query.setPageSize(999999999);
        query.addProjection(Projections.count());
        query.setQueryType(QueryType.JDBC);
        if (status != null) {
            query.inArray("status", status);
        }
        Date currentDate = null;
        if (date != null) {
            SimpleDateFormat formate = new SimpleDateFormat(DateTimeUtil.DATE_FORMAT_YMD);
            try {
                currentDate = formate.parse(DateTimeUtil.formatShortStr(date));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 0;
            }
            if (null != currentDate) {
                query.ge("createTime", currentDate);
            }
        }

        return serviceFactory.getPersistService().count(query);
    }

    // 统计用户注册情况
    private long getUserCount(UserInfoStatus stastus, Date date) {
        DynamicQuery query = new DynamicQuery(UserInfo.class);
        query.addProjection(Projections.count());
        query.setPageSize(999999999);
        query.setQueryType(QueryType.JDBC);
        if (null != stastus) {
            query.eq("status", stastus);
        }
        Date currentDate = null;
        if (null != date) {
            SimpleDateFormat formate = new SimpleDateFormat(DateTimeUtil.DATE_FORMAT_YMD);
            try {
                currentDate = formate.parse(DateTimeUtil.formatShortStr(date));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 0;
            }
            if (null != currentDate) {
                query.ge("registerTime", currentDate);

            }
        }

        return serviceFactory.getPersistService().count(query);
    }

    // 统计交易数
    private String getTradeAccount(InvestStatus status) {
        DynamicQuery query = new DynamicQuery(InvestInfo.class);
        query.addProjection(Projections.count());
        query.eq("status", status);
        query.setPageSize(999999999);
        query.setQueryType(QueryType.JDBC);
        return serviceFactory.getPersistService().count(query) + "";
    }

    // 统计交易总额
    private String getTradeAmount(InvestStatus status) {
        DynamicQuery query = new DynamicQuery(InvestInfo.class);
        query.addProjection(Projections.sum("investMoney", "investMoneySum"));
        query.eq("status", status);// InvestStatus.SUCESS
        query.setQueryType(QueryType.JDBC);
        List list = serviceFactory.getPersistService().find(null, query);
        if (null == list || list.isEmpty()) {
            return "0";
        } else {
            return MoneyUtil.convertFenToYuan(Long.parseLong(list.get(0) == null ? "0" : list.get(0) + ""));
        }
    }
}
